<?php

// 应用公共文件
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use service\DataService;
use service\NodeService;
use think\Cache;
use think\Db;
use PHPExcel;
use PHPExcel_IOFactory;

/**
 * RBAC节点权限验证
 * @param string $node
 * @return bool
 */
function auth($node)
{
    return NodeService::checkAuthNode($node);
}

/**
 * 设备或配置系统参数
 * @param string $name 参数名称
 * @param bool $value 默认是null为获取值，否则为更新
 * @return string|bool
 */
function sysconf($name, $value = null)
{
//    static $config = [];
//    if ($value !== null) {
//        list($config, $data) = [[], ['name' => $name, 'value' => $value]];
//        return DataService::save('SystemConfig', $data, 'name');
//    }
//    if (empty($config)) {
//        $config = Db::name('SystemConfig')->column('name,value');
//    }
//    return isset($config[$name]) ? $config[$name] : '';
}

/**
 * 日期格式化
 * @param string $date 标准日期格式
 * @param string $format 输出格式化date
 * @return false|string
 */
function format_datetime($date, $format = 'Y年m月d日 H:i:s')
{
    return empty($date) ? '' : date($format, strtotime($date));
}

/**
 * 格式化菜单数据  多个下级
 * @param $data 原始数据
 * @param string $pk 主键
 * @param string $parent_name 上级的 字段
 * @param string $parent_value 一级的默认值
 * @param string $sub 下级字段的别名
 * @return array
 */
function formatData($data, $pk ='id', $parent_name = 'parent_id', $parent_value = '0', $sub = 'sub'){
    $new = [];
    foreach ($data as $k => $v){
        if(isset($v[$parent_name]) &&  $v[$parent_name] == $parent_value){
            unset($data[$k]);
            $v[$sub] = formatData($data,$pk,$parent_name,$v[$pk]);
            $new[] = $v;
        }
    }
    return $new;
}

//上传文件
function uploads(){
    switch (config("upload")){
        case 'qiniu':
            return qiniu_upload();
            break;
        case 'localhost':
            return localhost_upload();
            break;
        default:
            return localhost_upload();
    }
}

//上传图片到本地 public/uploads
function localhost_upload()
{
    $file = request()->file('file','');
    if($file){
        $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
        if($info){
            // 成功上传后 获取上传信息
            // 输出 jpg
            $info->getExtension();
            // 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg
            $file_name = '/uploads/'.$info->getSaveName();
            // 输出 42a79759f284b767dfcb2a0197904287.jpg
            $info->getFilename();
        }else{
            // 上传失败获取错误信息
            $file_name = $file->getError();
        }
    }

    $data = [
        'code'  => 0,
        'msg'   => '上传成功',
        'data'  => $file_name,
        'url'   => $file_name
    ];
    return json($data);
}

//七牛上传图片
function qiniu_upload()
{
    $file = request()->file('file');
    // 要上传图片的本地路径
    $filePath = $file->getRealPath();
    $ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);  //后缀
    // 上传到七牛后保存的文件名
    $key =substr(md5($file->getRealPath()) , 0, 5). date('YmdHis') . rand(0, 9999) . '.' . $ext;
    // 需要填写你的 Access Key 和 Secret Key
    // 构建鉴权对象
    $accessKey =config("qiniu")["accessKey"];
    $secretKey =config("qiniu")["secretKey"];
    $auth=new Auth($accessKey,$secretKey);
    // 要上传的空间
    $bucket =config("qiniu")["bucket"];
    //域名
    $domain=config("qiniu")["domain"];
    $token = $auth->uploadToken($bucket);
    // 初始化 UploadManager 对象并进行文件的上传
    $uploadMgr = new UploadManager();
    // 调用 UploadManager 的 putFile 方法进行文件的上传
    list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
    if ($err !== null) {
        return ["err"=>1,"msg"=>$err,"data"=>""];
    } else {
        //返回图片的完整URL
        $imgPath=$domain.'/'.$key;
    }

    $data = [
        'code'  => 0,
        'msg'   => '上传成功',
        'data'  => $imgPath,
        'url'   => $imgPath
    ];
    return json($data);
}

//权限和登录的判断跳转
function goto_login($msg,$url){
    echo "<html>";
    echo "<script>";
    echo "alert('".$msg."');";
    echo "window.open ('".$url."','_top')";
    echo "</script>";
    echo "</html>";
    exit();
}

//缓存使用 redis
function cache_cqy(){
    Cache::store('redis')->set('ff',time(),300);
    echo Cache::store('redis')->get('ff');
}

//导出数据  excel
    /**
    $res = $db->whereIn('id',$ids)->select();
    $xlsName  = "article";
    $xlsCell  = array(
        array('name','名称'),
        array('sort','电话'),
        array('status','金额'),
        array('content','df'),
        array('top','是否有房')
    );
    exportExcel($xlsName,$xlsCell,$res)
     */
function exportExcel($expTitle,$expCellName,$expTableData){
    $xlsTitle = iconv('utf-8', 'gb2312', $expTitle);//文件名称
    $fileName =date('_YmdHis');//or $xlsTitle 文件名称可根据自己情况设定
    $cellNum = count($expCellName);
    $dataNum = count($expTableData);
    vendor("PHPExcel.PHPExcel");

    $objPHPExcel = new PHPExcel();
    $cellName = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ');

    for($i=0;$i<$cellNum;$i++){
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i].'1', $expCellName[$i][1]);
    }
    for($i=0;$i<$dataNum;$i++){
        for($j=0;$j<$cellNum;$j++){
            $objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j].($i+2), $expTableData[$i][$expCellName[$j][0]]);

        }
    }
    header('pragma:public');
    header('Content-type:application/vnd.ms-excel;charset=utf-8;name="'.$xlsTitle.'.xls"');
    header("Content-Disposition:attachment;filename=$fileName.xls");//attachment新窗口打印inline本窗口打印
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
    $objWriter->save('php://output');
    exit;
}

/**
 * 获取广告信息 （默认排序：sort升序）
 * @param $act 广告位的 标志
 * @param int $limit 显示条数
 * @return false|PDOStatement|string|\think\Collection
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function getAd($act, $limit = 3){
    $res = Db::table('ad_position')
        ->alias('ap')
        ->field('ad.*,ap.act')
        ->join('ad','ad.position_id = ap.id')
        ->whereIn('ap.act', $act)
        ->where('ap.status', 1)
        ->where('ad.status', 1)
        ->order('ad.sort')
        ->limit($limit)
        ->select();
    return $res;
}

/**
 * 获取文章信息 （默认排序：id降序）
 * @param $act 标签的标志
 * @param int $limit 显示条数
 * @param string $sort
 * @return false|PDOStatement|string|\think\Collection
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function getArticleByTag($act, $limit = 6, $sort = 'a.id DESC'){
    if(!is_array($act)){
        $acts[] = $act;
    }else{
        $acts = $act;
    }

    $res = Db::table('tag')
        ->alias('t')
        ->field('a.*,t.act')
        ->join('article_tag at','at.tag_id = t.id')
        ->join('article a','at.article_id = a.id')
        ->whereIn('t.act', $acts)
        ->where('t.status', 1)
        ->where('a.status', 1)
        ->order($sort)
        ->limit($limit)
        ->select();
    return $res;

}

function createRandom($length = 6){
    $chrs = array('1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z');
    $str = '';
    for($i=1;$i<=$length;$i++){
        shuffle($chrs);
        $str.=$chrs[0];
    }
    return $str;
}

function getAreas($parent_id = -1){
    return Db::table('areas')->where('parent_id', $parent_id)->column('name','id');
}

function dd($res=''){
    if($res){
        var_dump($res);
        exit('');
    }else{
        echo date('Y-m-d H:i:s');
        exit('');
    }
}

function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true){
    if(function_exists("mb_substr")){
        $slice= mb_substr($str, $start, $length, $charset);
    }elseif(function_exists('iconv_substr')) {
        $slice= iconv_substr($str,$start,$length,$charset);
    }else{
        $re['utf-8'] = "/[x01-x7f]|[xc2-xdf][x80-xbf]|[xe0-xef][x80-xbf]{2}|[xf0-xff][x80-xbf]{3}/";
        $re['gb2312'] = "/[x01-x7f]|[xb0-xf7][xa0-xfe]/";
        $re['gbk'] = "/[x01-x7f]|[x81-xfe][x40-xfe]/";
        $re['big5'] = "/[x01-x7f]|[x81-xfe]([x40-x7e]|xa1-xfe])/";
        preg_match_all($re[$charset], $str, $match);
        $slice = join("",array_slice($match[0], $start, $length));
    }
    $fix='';
    if(strlen($slice) < strlen($str)){
        $fix='...';
    }
    return $suffix ? $slice.$fix : $slice;
}

if (!function_exists("isMobile")) {
    function isMobile()
    {
        $user_agent = $_SERVER['HTTP_USER_AGENT'];
        $mobile_agents = array ('iphone','android','phone','mobile','wap','netfront','java','opera mobi',
            'opera mini','ucweb','windows ce','symbian','series','webos','sony','blackberry','dopod',
            'nokia','samsung','palmsource','xda','pieplus','meizu','midp','cldc','motorola','foma',
            'docomo','up.browser','up.link','blazer','helio','hosin','huawei','novarra','coolpad',
            'techfaith','alcatel','amoi','ktouch','nexian','ericsson','philips','sagem','wellcom',
            'bunjalloo','maui','smartphone','iemobile','spice','bird','zte-','longcos','pantech',
            'gionee','portalmmm','jig browser','hiptop','benq','haier','^lct','320x320','240x320',
            '176x220','windows phone','cect','compal','ctl','lg','nec','tcl','daxian','dbtel','eastcom',
            'konka','kejian','lenovo','mot','soutec','sgh','sed','capitel','panasonic','sonyericsson',
            'sharp','panda','zte','acer','acoon','acs-','abacho','ahong','airness','anywhereyougo.com',
            'applewebkit/525','applewebkit/532','asus','audio','au-mic','avantogo','becker','bilbo',
            'bleu','cdm-','danger','elaine','eric','etouch','fly ','fly_','fly-','go.web','goodaccess',
            'gradiente','grundig','hedy','hitachi','htc','hutchison','inno','ipad','ipaq','ipod',
            'jbrowser','kddi','kgt','kwc','lg ','lg2','lg3','lg4','lg5','lg7','lg8','lg9','lg-','lge-',
            'lge9','maemo','mercator','meridian','micromax','mini','mitsu','mmm','mmp','mobi','mot-',
            'moto','nec-','newgen','nf-browser','nintendo','nitro','nook','obigo','palm','pg-',
            'playstation','pocket','pt-','qc-','qtek','rover','sama','samu','sanyo','sch-','scooter',
            'sec-','sendo','sgh-','siemens','sie-','softbank','sprint','spv','tablet','talkabout',
            'tcl-','teleca','telit','tianyu','tim-','toshiba','tsm','utec','utstar','verykool','virgin',
            'vk-','voda','voxtel','vx','wellco','wig browser','wii','wireless','xde','pad','gt-p1000');
        $ismobile = false;
        foreach ($mobile_agents as $device) {
            if (stristr($user_agent, $device)) {
                $ismobile = true;
                break;
            }
        }
        return $ismobile;
    }
}
